package com.bdqn.crm.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.crm.pojo.SysRight;
import com.bdqn.crm.pojo.SysRole;
import com.bdqn.crm.pojo.SysUser;
import com.bdqn.crm.service.SysRoleService;
import com.bdqn.crm.service.SysUserService;
import com.bdqn.crm.utils.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //redis中数据的key的前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count_";


    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleService roleService;

    @RequestMapping("/doLogin")
    public String dologin(String usrName, String usrPassword, Model model, HttpServletRequest request) {
//        System.out.println("进来了");
//        SysUser user = userService.login(usrName,usrPassword);
//        System.out.println("123"+ JSON.toJSONString(user));
//        if(user!=null){
//            request.getSession().setAttribute("loginUser",user);
//            return "main";
//        }else{
//            request.setAttribute("message","登录失败，用户名或密码错误！");
//            return "login";
//        }
        try {
            //在Shiro配置文件中使用了HashedCredentialsMatcher密码验证器，所以不需要下面的代码进行加密了
//            usrPassword = userService.encryptPassword(usrPassword);//封装之前先进行加密
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);   //认证、登录
            //认证(登录)成功，清空登录计数
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT+usrName);
            //认证（登录）成功
            SysUser user = (SysUser) subject.getPrincipal();
            SysRole role = user.getRole();  //如果一对多关联不是立即加载，则需要通过用户获取角色
            List<SysRight> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);

            request.getSession().setAttribute("loginUser", user);
            return "redirect:/main";    //建议重定向
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("message", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("message", "用户被禁用,登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("message", "账号1小时内禁止登录!");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();    //Shiro注销
        return "redirect:/index"; //建议重定向，保证删除Cookie
    }

    //    @GetMapping("/user/list")
//    public String list(Model model,String usrName, @RequestParam(required = false,defaultValue = "0") Long roleId, @RequestParam(required = false,defaultValue = "1") int pageIndex){
//        Page<SysUser> page = new Page<>(pageIndex,5);
//        page.setTotal(userService.count());
//        page.setRecords(userService.selectPages(usrName,roleId,(page.getCurrent()-1)*page.getPageSize(),page.getPageSize()));
//        System.out.println(JSON.toJSONString(page));
//        model.addAttribute("userPager",page);
//        return "user/list";
//    }
    @RequestMapping("/user/list")
    public String postList(HttpServletRequest request, Model model, String usrName, @RequestParam(required = false, defaultValue = "0") Long roleId, @RequestParam(required = false, defaultValue = "1") int pageIndex) {
        System.out.println("request==>" + JSON.toJSONString(request.getParameterMap()));
        Page<SysUser> page = new Page<>(pageIndex, 5);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        //判断是否有查询条件
        if (usrName != null && usrName.trim() != "") {
            queryWrapper.like("usr_name", usrName);      //模糊设置条件
        }
        if (roleId != 0) {
            queryWrapper.eq("usr_role_id", roleId);
        }

        if (userService.count(queryWrapper) == 0) {     //此操作说明 数据库没有数据可展示，那么就全部清零
            page.setTotalElements(0);
            page.setContent(null);
        } else {
            page.setTotalElements(userService.count(queryWrapper));
            page.setContent(userService.selectPages(usrName, roleId, (page.getNumber() - 1) * page.getPageSize(), page.getPageSize()));
        }

        System.out.println(JSON.toJSONString(page));

        List<SysRole> roles = roleService.list();
        model.addAttribute("usrName", usrName);
        model.addAttribute("roles", roles);
        model.addAttribute("roleId", roleId);
        model.addAttribute("userPager", page);
        return "user/list";
    }

    @GetMapping("user/add")
    public String toUserAdd(Model model) {
        List<SysRole> roles = roleService.list();
        model.addAttribute("roles", roles);
        return "user/add";
    }

    @PostMapping("user/save")
    public String userSave(SysUser user) {
        System.out.println("JSONtoJSONString==>" + JSON.toJSONString(user));
        userService.saveOrUpdate(user);
        return "redirect:/user/list";
    }

    @GetMapping("user/edit")
    @RequiresPermissions(value = "用户编辑")
    public String edit(Long usrId, Model model) {
        SysUser sysUser = userService.getById(usrId);
        List<SysRole> roles = roleService.list();
        model.addAttribute("user", sysUser);
        model.addAttribute("roles", roles);
        return "user/edit";
    }

    @ResponseBody
    @GetMapping(value = "user/del/{usrId}", produces = "text/html; charset=UTF-8")
    public String userDel(Map<String, String> map, @PathVariable("usrId") Long usrId) {
        if (userService.removeById(usrId)) {
            map.put("delResult", "true");
        }
        return JSON.toJSONString(map);
    }

}
